import router from "./router";
import store from "./store";
import getPageTitle from '@/utils/get-page-title.js'

const whiteList = ["/login"]; // no redirect whitelist

router.beforeEach(async (to, from, next) => {

  // set page title
  document.title = getPageTitle(to.meta.title);

  const hasToken = store.state.user.token;

  if (hasToken) {
    if (to.path === "/login") {
      // if is logged in, redirect to the home page
      next({
        path: "/"
      });
    } else {
      const hasGetUserName = store.getters.name;
      // vuex是否存在用户名
      if (hasGetUserName) {
        next();
      } else {
        // 不存在通过接口获取
        try {
          //获取用户信息
          await store.dispatch("user/getInfo");
          next();
        } catch (error) {
          // 删除用户信息跳转到登录页面
          await store.dispatch("user/resetToken");
          Message.error(error || "Has Error");
          next(`/login?redirect=${to.path}`);
        }
      }
    }
  } else {
    // token不存在
    if (whiteList.indexOf(to.path) !== -1) {
      // 白名单页面直接通过
      next();
    } else {
      // 其他页面，并且未登录，跳转登录
      next(`/login?redirect=${to.path}`);
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  // NProgress.done()
});